package com.erastep.util
{
	import mx.collections.ArrayCollection;
	import mx.collections.ArrayList;
	import mx.utils.ObjectUtil;

	public class JsonParser
	{
		private var baseType:ArrayCollection=new ArrayCollection();

		public function JsonParser()
		{
			baseType.addItem("int");
			baseType.addItem("string");
			baseType.addItem("boolean");
			baseType.addItem(null);
		}

		public function encode(source:Object):String
		{
			var str:String="{";
			str += main(source) + "}";
			return str;
		}

		private function main(source:Object):String
		{
			var str:String="";
			if (source is ArrayCollection || source is ArrayList)
			{
				source=source.source;
			}
			if (source is Array)
			{
				str+=encodeArray(source);
			}
			else
			{
				var properties:Array=StringUtil.getProperties(source);
				if (properties.length < 1)
				{
					return "''";
				}
				for each (var item:String in properties)
				{
					var value:Object=source[item];
					var flag:Boolean=false;
					if(value is Array)
						flag = true;
					if (value is ArrayCollection)
					{
						flag=true;
						value=value.source;
					}
					if (null == value || value.length < 1)
					{
						if (flag)
						{
							str+="\"" + item + "\":[],";
						}
						else
							str+="\"" + item + "\":\"null\",";
					}
					else if (baseType.contains(typeof(value)))
					{
						processValue(value + "");
						str+="\"" + item + "\":\"" + value + "\",";
					}
					else
						str+="\"" + item + "\":" + main(value) + ",";
				}
				if (properties.length > 0)
				{
					str=str.substring(0, str.length - 1);
				}
			}
			return str.toString();
		}
		
		private function processValue(value:String):void{
			value = StringUtil.replace(value, "\"","\\\"");
		}

		private function encodeArray(source:Object):String
		{
			var str:String="[";
			var array:Array=source as Array;
			for each (var item:Object in array)
			{
				if (item is Array || item is ArrayCollection)
				{
					str+=encodeArray(item);
				}
				else
				{
					str+="{";
					var properties:Array=StringUtil.getProperties(item);
					for each (var property:String in properties){
						if(item && item.hasOwnProperty(property)){
							processValue(item[property]);
						}
						str+="\"" + property + "\":\"" + item[property] + "\",";
					}
					if (properties.length > 0)
					{
						str=str.substring(0, str.length - 1);
					}
					str+="},";
				}
			}
			if (array.length > 0)
			{
				str=str.substring(0, str.length - 1);
			}
			str+="]";
			return str;
		}

	}
}